package com.gqb.daemonThread;

import java.util.ArrayDeque;
import java.util.Date;
import java.util.Deque;

public class DaemonThread extends Thread {

	private Deque<Event> deque;
	
	
	public DaemonThread(Deque<Event> deque) {
		super();
		this.deque = deque;
		setDaemon(true);
	}


	@Override
	public void run() {
		while(true){
			Date date=new Date();
			clean(date);
		}
	}
	
	private void clean(Date date){
		long dif;
		boolean delete;
		if(deque.size()==0){
			return;
		}
		delete=false;
		do{
			Event e=deque.getLast();
			dif=date.getTime()-e.getDate().getTime();
			if(dif>10000){
				System.out.println("delete thread "+e.getThread());
				deque.removeLast();
				delete=true;
			}
		}while(dif>10000);
		if(delete){
			System.out.println("cleaner: size of deque is "+deque.size());
		}
	}
	public static void main(String[] args) {
		Deque<Event> deque=new ArrayDeque<Event>();
		WriterTask task=new WriterTask(deque);
		for (int i = 0; i < 3; i++) {
			Thread t=new Thread(task);
			t.start();
		}
		DaemonThread thread=new DaemonThread(deque);
		thread.start();
	}
	
	
}
